from django.shortcuts import render
import json
from django.views.decorators.csrf import csrf_exempt
from influxdb import InfluxDBClient
from django.http import HttpResponse
import subprocess
from app import models


# subprocess to write in database
def MyMonitor_subprocess():
    cmd = "python ./monitor.py"
    subprocess.Popen(cmd, shell=True)


MyMonitor_subprocess()


# subprocess to ssh
def ssh_subprocess(ip, username, pwd):
    cmd = f"python ./ssh.py {ip} {username} {pwd}"
    subprocess.Popen(cmd, shell=True)


# get all data from database
info_list = models.virtual_and_server_ip.objects.all()


@csrf_exempt
def index(request):
    # 查询出Person对象信息，也就是数据表中的所有数据
    # 一行数据就是一个对象，一个格子的数据就是一个对象的一个属性值
    if request.method == "POST":
        t = request.POST.get("vs",None)
        ips = request.POST.get("ips", None)
        i = request.POST.get("ip", None)
        u = request.POST.get("username", None)
        p = request.POST.get("pwd", None)

        t_delete = request.POST.get("vs_delete",None)
        ips_delete = request.POST.get("ips_delete", None)
        i_delete = request.POST.get("ip_delete", None)
        u_delete = request.POST.get("username_delete", None)
        p_delete = request.POST.get("pwd_delete", None)

        if ips_delete != "" and t_delete != '' and i_delete != '' and u_delete != '' and p_delete != '':
            models.virtual_and_server_ip.objects.get(ip=i_delete).delete()

        # ---------表中插入数据
        if ips!="" and t != "" and i != '' and u != '' and p != '':
            models.virtual_and_server_ip.objects.get_or_create(
                type=t,
                ips=ips,
                ip=i,
                username=u,
                pwd=p,
            )
    global info_list
    info_list = models.virtual_and_server_ip.objects.all()
    for i in info_list:
        print(i.ip, i.username, i.pwd)
        ssh_subprocess(i.ip, i.username, i.pwd)

    return render(request, "index.html", {"info_list": info_list})


#  ResultSet转化为list格式
def ResultSet_to_list(ResultSet):
    for elem in ResultSet:
        return elem

#  获取当前时刻信息
def get_all_current_host():
    client = InfluxDBClient('localhost', 8086, 'root', '123456', 'my_monitor')
    L = client.query('SELECT * from all_info ORDER BY time DESC LIMIT 1')
    L = ResultSet_to_list(L)
    L[0]['time'] = L[0]['time'].split('.')[0]
    return L

#  获取历史时刻信息
def get_all_history_host():
    client = InfluxDBClient('localhost', 8086, 'root', '123456', 'my_monitor')
    L = client.query('SELECT * from average_info')
    L = ResultSet_to_list(L)
    L_date = []
    if L is not None:
        for elem in L:
            L_date.append(elem['time'])
            del elem['time']

    return [L_date, L]

#  把数据返回给前端
def select_info(request):
    L1 = get_all_current_host()
    L2 = get_all_history_host()
    L_json = {'currentData': {'data': L1}, 'historyData': {'date': L2[0], 'data': L2[1]}}
    L = json.dumps(L_json)
    return HttpResponse(L)

#  获取远程监控虚拟机的当前时刻信息
def get_all_current_ssh(username):
    client = InfluxDBClient('localhost', 8086, 'root', '123456', f'{username}')
    L = client.query('SELECT * from all_info ORDER BY time DESC LIMIT 1')
    if L != "":
        L = ResultSet_to_list(L)
        L[0]['time'] = L[0]['time'].split('.')[0]
    return L

#  获取远程监控虚拟机的历史时刻信息
def get_all_history_ssh(username):
    client = InfluxDBClient('localhost', 8086, 'root', '123456', f'{username}')
    L = client.query('SELECT * from average_info')
    L = ResultSet_to_list(L)
    L_date = []
    if L is not None:
        for elem in L:
            L_date.append(elem['time'])
            del elem['time']

    return [L_date, L]

#  把远程监控虚拟机的数据返回给前端
def ssh_info(request):
    L_json = {}
    L_c = []
    for i in info_list:
        L_current = get_all_current_ssh(i.username)
        L_history = get_all_history_ssh(i.username)
        L_c.append(L_current[0])
        # historyData show the newest ip info
        L_json = {'currentData': {'data': L_c},
                  'historyData': {'date': L_history[0], 'data': L_history[1]}}
    L = json.dumps(L_json)
    return HttpResponse(L)


def show_vs(request):
    vs_list = models.virtual_and_server_ip.objects.all()
    L_ips = []
    L_ip = []
    for vs in vs_list:
        L_ips.append(vs.ips)
        L_ip.append(vs.ip)
    L_json = {'data': {'serverIp': L_ips, 'virtualIp': L_ip}}
    L = json.dumps(L_json)
    return HttpResponse(L)